package com.sd.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.jfinal.plugin.activerecord.Record;

import java.util.Collections;

/**
 * 多叉树类
 */
public class MultipleTree {

	private String sql = "";

	public static String getTree(List<Record> dataList) {
		// 读取层次数据结果集列表

		// 节点列表（散列表，用于临时存储节点对象）
		HashMap<Integer, Node> nodeList = new HashMap<Integer, Node>();
		// 根节点
		Children root = new Children();
		// 根据结果集构造节点列表（存入散列表）
		for (Iterator<Record> it = dataList.iterator(); it.hasNext();) {
			Record dataRecord = it.next();
			Node node = new Node();
			node.dict_id = Integer.parseInt(dataRecord.get("dict_id").toString());
			node.dict_name = (String) dataRecord.get("dict_name");
			node.english_name = (String) dataRecord.get("english_name");
			node.icon = (String) dataRecord.get("icon");
			node.url = (String) dataRecord.get("url");
			node.remark = (String) dataRecord.get("remark");
			node.sort = Integer.parseInt(dataRecord.get("sort").toString());
			node.p_id = Integer.parseInt(dataRecord.get("p_id").toString());
			nodeList.put(node.dict_id, node);
		}
		// 构造无序的多叉树
		Set<?> entrySet = nodeList.entrySet();
		Iterator<?> it = entrySet.iterator();
		try{
			
			while (it.hasNext()) {
				Node node =  (Node) ((Map.Entry) it.next()).getValue();
				if (node.p_id == 0) {
					root.addChild(node);
				} else if(nodeList.get(node.p_id)!=null) {
					nodeList.get(node.p_id).addChild(node);
				}
			}

		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		// 输出无序的树形菜单的JSON字符串
		// System.out.println(root.toString());
		// 对多叉树进行横向排序
		root.sortChildren();
		// 输出有序的树形菜单的JSON字符串
		System.out.println(root.toString());
		return root.toString();
	}

}

/**
 * 节点类
 */
class Node {
	/**
	 * 节点编号
	 */
	public int dict_id;
	/**
	 * 模块名称
	 */
	public String dict_name;
	/**
	 * 父节点编号
	 */
	public int p_id;
	/**
	 * 图标
	 */
	public String icon;
	/**
	 * 英文id
	 */
	public String english_name;
	/**
	 * 英文id
	 */
	public String url;
	/**
	 * 排序标示
	 */
	public int sort;
	/**
	 * 备注
	 */
	public String remark;
	/**
	 * 孩子节点列表
	 */
	private Children children = new Children();

	// 先序遍历，拼接JSON字符串
	public String toString() {
		String result = "{" + "'dict_id' : " + dict_id + ", 'dict_name' : '" + dict_name + "'" + ", 'icon' : '" + icon
				+ "'" + ", 'english_name' : '" + english_name + "'" + ", 'url' : '" + url + "'"
				+ ", 'remark' : '" + remark + "'";

		if (children != null && children.getSize() != 0) {
			result += ", 'children' : " + children.toString();
		} else {
			result += ", 'leaf' : true";
		}

		return result + "}";
	}

	// 兄弟节点横向排序
	public void sortChildren() {
		if (children != null && children.getSize() != 0) {
			children.sortChildren();
		}
	}

	// 添加孩子节点
	public void addChild(Node node) {
		this.children.addChild(node);
	}
}

/**
 * 孩子列表类
 */
class Children {
	private List<Node> list = new ArrayList<Node>();

	public int getSize() {
		return list.size();
	}

	public void addChild(Node node) {
		list.add(node);
	}

	// 拼接孩子节点的JSON字符串
	public String toString() {
		String result = "[";
		for (Iterator<Node> it = list.iterator(); it.hasNext();) {
			result += it.next().toString();
			result += ",";
		}
		result = result.substring(0, result.length() - 1);
		result += "]";
		return result;
	}

	// 孩子节点排序
	public void sortChildren() {
		// 对本层节点进行排序
		// 可根据不同的排序属性，传入不同的比较器，这里传入ID比较器
		Collections.sort(list, new NodeIDComparator());
		// 对每个节点的下一层节点进行排序
		for (Iterator<Node> it = list.iterator(); it.hasNext();) {
			it.next().sortChildren();
		}
	}
}

/**
 * 节点比较器
 */
class NodeIDComparator implements Comparator<Object> {
	// 按照节点编号比较
	public int compare(Object o1, Object o2) {
		int j1 = ((Node) o1).sort;
		int j2 = ((Node) o2).sort;
		return (j1 < j2 ? -1 : (j1 == j2 ? 0 : 1));
	}
}
